package com.slipper.system.menu.service;

import java.util.List;
import java.util.Set;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.slipper.common.util.StringUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import com.slipper.system.menu.dao.MenuPrivilegeDao;
import com.slipper.system.api.menu.bo.MenuPrivilegeBO;

import com.slipper.common.transaction.ReadTransactional;
import com.slipper.common.transaction.WriteTransactional;
import com.slipper.common.util.Tool;

@Service
@ReadTransactional
public class MenuPrivilegeService {
    @Resource
    private MenuPrivilegeDao menuPrivilegeDao;
    
    public MenuPrivilegeBO queryBy(String id) {
        return menuPrivilegeDao.queryBy(id);
    }
    
    public List<MenuPrivilegeBO> queryList(MenuPrivilegeBO bo) {
        return menuPrivilegeDao.queryList(bo);
    }
    
    public PageInfo<MenuPrivilegeBO> queryPage(MenuPrivilegeBO bo) {
        PageHelper.startPage(bo.getPageNumber(), bo.getPageSize());
        return new PageInfo<>(menuPrivilegeDao.queryList(bo));
    }

    @WriteTransactional
    public int save(String menuId, Set<MenuPrivilegeBO> privilegeList) {
        if (StringUtil.isBlank(menuId)) {
            return 0;
        }

        if (privilegeList.isEmpty()) {
            return menuPrivilegeDao.deleteByMenuId(menuId);
        }

        // 删除已被删除的数据
        MenuPrivilegeBO menuPrivilegeQO = new MenuPrivilegeBO();
        menuPrivilegeQO.setMenuId(menuId);
        List<MenuPrivilegeBO> persitList = menuPrivilegeDao.queryList(menuPrivilegeQO);
        persitList.forEach(persist -> {
            if (privilegeList.stream().noneMatch(item -> persist.getId().equals(item.getId()))) {
                menuPrivilegeDao.delete(persist);
            }
        });

        // 先删除后保存，避免误删除
        privilegeList.forEach(privilege -> {
            privilege.setMenuId(menuId);
            this.save(privilege);
        });

        return 1;
    }
    
    @WriteTransactional
    public int save(MenuPrivilegeBO bo) {
        int result;
        if (StringUtil.isNotBlank(bo.getId())) {

            MenuPrivilegeBO menuPrivilegeBO = menuPrivilegeDao.queryBy(bo.getId());
            if (menuPrivilegeBO == null) {
                result = menuPrivilegeDao.insert(bo);
            } else {
                if (bo.getOrdinal() == null) {
                    bo.setOrdinal(menuPrivilegeBO.getOrdinal());
                }
                result = menuPrivilegeDao.update(bo);
            }
        } else {
            bo.setId(Tool.getUUID());
            result = menuPrivilegeDao.insert(bo);
        }
        return result;
    }
    
    @WriteTransactional
    public int delete(MenuPrivilegeBO bo) {
        return menuPrivilegeDao.delete(bo);
    }

    @WriteTransactional
    public int deleteByMenuId(String menuId) {
        return menuPrivilegeDao.deleteByMenuId(menuId);
    }
}
